import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, message } from 'antd';
import { useMeituanData } from '../hooks/useMeituanData';
import { useErrorHandler } from '../services/errorHandler';

const { TextArea } = Input;
const { Option } = Select;

/**
 * 操作模态框组件
 * 用于订单处理、团购券使用等操作
 */
const ActionModal = ({
  visible,
  onCancel,
  onSuccess,
  order,
  actionType = 'process', // process | use | sync
  title,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const { processOrder, useVoucher, syncOrders } = useMeituanData();
  const { execute } = useErrorHandler();

  // 根据操作类型获取标题
  const getTitle = () => {
    if (title) return title;
    switch (actionType) {
      case 'process':
        return '处理订单';
      case 'use':
        return '使用团购券';
      case 'sync':
        return '同步订单';
      default:
        return '操作确认';
    }
  };

  // 根据操作类型获取确认按钮文字
  const getOkText = () => {
    switch (actionType) {
      case 'process':
        return '确认处理';
      case 'use':
        return '确认使用';
      case 'sync':
        return '立即同步';
      default:
        return '确认';
    }
  };

  // 处理提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      let result;
      switch (actionType) {
        case 'process':
          result = await execute(() => 
            processOrder(order.id, values.status, values.remark)
          );
          break;
        case 'use':
          result = await execute(() => 
            useVoucher(order.id)
          );
          break;
        case 'sync':
          result = await execute(() => 
            syncOrders({ store_id: order.store_id })
          );
          break;
        default:
          break;
      }

      if (result !== false) {
        message.success('操作成功');
        onSuccess?.(result);
        handleCancel();
      }
    } catch (error) {
      console.error('操作失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 取消操作
  const handleCancel = () => {
    form.resetFields();
    onCancel?.();
  };

  // 渲染表单内容
  const renderFormContent = () => {
    switch (actionType) {
      case 'process':
        return (
          <>
            <Form.Item
              label="订单号"
              name="orderId"
              initialValue={order?.order_id}
            >
              <Input disabled />
            </Form.Item>
            
            <Form.Item
              label="处理状态"
              name="status"
              rules={[{ required: true, message: '请选择处理状态' }]}
            >
              <Select placeholder="请选择处理状态">
                <Option value={1}>已接单</Option>
                <Option value={2}>已拒绝</Option>
                <Option value={3}>已完成</Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="备注"
              name="remark"
            >
              <TextArea 
                rows={3} 
                placeholder="请输入处理备注（可选）"
                maxLength={200}
                showCount
              />
            </Form.Item>
          </>
        );

      case 'use':
        return (
          <>
            <p>确认要使用团购券吗？</p>
            <p>订单号：{order?.order_id}</p>
            <p>团购商品：{order?.group_title}</p>
            <p>用户：{order?.user_name}</p>
          </>
        );

      case 'sync':
        return (
          <>
            <p>确认要同步订单数据吗？</p>
            <p>门店：{order?.store_name}</p>
            <p>这将从美团API获取最新的订单数据。</p>
          </>
        );

      default:
        return null;
    }
  };

  return (
    <Modal
      title={getTitle()}
      open={visible}
      onOk={handleSubmit}
      onCancel={handleCancel}
      confirmLoading={loading}
      okText={getOkText()}
      cancelText="取消"
      width={actionType === 'process' ? 520 : 400}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        preserve={false}
      >
        {renderFormContent()}
      </Form>
    </Modal>
  );
};

export default ActionModal;